package com.qf.service.impl;

import com.alibaba.fastjson.JSON;
import com.qf.common.R;
import com.qf.core.ParseRequestData;
import com.qf.dto.StudentDto;
import com.qf.dto.StudentsInfo;
import com.qf.dto.UserRoleDto;
import com.qf.mapper.StudentMapper;
import com.qf.mapper.impl.StudentMapperImpl;
import com.qf.pojo.Page;
import com.qf.pojo.Student;
import com.qf.service.StudentService;
import com.qf.utils.CookieUtils;
import com.qf.utils.DtoUtils;
import com.qf.utils.PageUtils;
import com.qf.utils.ParseRequestDataUtils;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class StudentServiceImpl implements StudentService {

    private StudentMapper studentMapper = new StudentMapperImpl();

    @Override
    public boolean isRegister(String username) {

        Student student = studentMapper.getStudent(username);
        if (student == null) {
            return true;
        }
        return false;
    }

    @Override
    public boolean register(HttpServletRequest request, HttpServletResponse response) throws IOException {

        ParseRequestData<Student> parseRequestData = ParseRequestDataUtils.parseRequest(request, Student.class, "upload\\student");

        Student stu = parseRequestData.getT();
        InputStream in = parseRequestData.getIn();
        if (in == null) {
            response.getWriter().write(JSON.toJSONString(R.fail("注册失败,用户头像不能为空")));
            return false;
        }
        OutputStream out = parseRequestData.getOut();

        boolean register = isRegister(stu.getUsername());
        if (register) {
            //将数据插入到学生表中
            studentMapper.add(stu.getUsername(), stu.getPassword(), stu.getName(), stu.getSex(), stu.getAge(), stu.getHobbies(), stu.getPhoto());

            //将头像存储到本地磁盘
            try {
                IOUtils.copy(in, out);
                in.close();
                out.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            Student student = studentMapper.getStudent(stu.getUsername());
            UserRoleDto userRoleDto = new UserRoleDto();
            userRoleDto.setName(student.getName());
            userRoleDto.setUsername(student.getUsername());
            userRoleDto.setPhoto(student.getPhoto());
            userRoleDto.setRole("student");
            response.getWriter().write(JSON.toJSONString(R.success("注册成功",userRoleDto)));
            return true;
        } else {
            try {
                in.close();
                out.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            response.getWriter().write(JSON.toJSONString(R.fail("该用户名已被注册")));
        }
        return false;
    }

    @Override
    public void initModify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        Student student = studentMapper.getStudent(username);
        response.getWriter().write(JSON.toJSONString(R.success("初始化成功",student)));
    }

    @Override
    public void modify(HttpServletRequest request, HttpServletResponse response) throws IOException {

        ParseRequestData<Student> parseRequestData = ParseRequestDataUtils.parseRequest(request, Student.class, "upload\\student");
        Student stu = parseRequestData.getT();
        InputStream in = parseRequestData.getIn();
        OutputStream out = parseRequestData.getOut();

        try {
            if (stu.getPhoto() != null) {//说明用户修改头像
                studentMapper.update(stu.getUsername(), stu.getName(), stu.getSex(), stu.getAge(), stu.getHobbies(), stu.getPhoto());
                IOUtils.copy(in, out);
            } else {
                studentMapper.update(stu.getUsername(), stu.getName(), stu.getSex(), stu.getAge(), stu.getHobbies());
            }
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Student student = studentMapper.getStudent(stu.getUsername());
        UserRoleDto userRoleDto = new UserRoleDto();
        userRoleDto.setName(student.getName());
        userRoleDto.setUsername(student.getUsername());
        userRoleDto.setPhoto(student.getPhoto());
        userRoleDto.setRole("student");
        response.getWriter().write(JSON.toJSONString(R.success("修改成功",userRoleDto)));
    }

    @Override
    public void getStudents(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取当前页数
        int curPage = Integer.parseInt(request.getParameter("curPage"));

        //设置URL
        String url = "student?action=doGetStudents&curPage=";
        //设置当前页的数据条数
        int count = 15;
        //计算偏移量
        int offset = (curPage - 1) * count;
        //计算总页数
        int allCount = studentMapper.getAllCount();
        int totalPage = PageUtils.getTotalPage(allCount, count);

        //从数据库获取学生的集合
        List<Student> students = studentMapper.getStudents(offset, count);

        //处理学生集合
        List<StudentDto> studentDtos = DtoUtils.studentDtoListHandler(students);

        StudentsInfo studentsInfo = new StudentsInfo(totalPage, studentDtos);
        System.out.println(studentsInfo);
        R result = R.success("查询学生列表成功", studentsInfo);
        String jsonString = JSON.toJSONString(result);
        response.getWriter().write(jsonString);
    }

    @Override
    public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        studentMapper.delete(username);
        response.getWriter().write(JSON.toJSONString(R.success("删除成功",null)));
    }
}
